const util = require('../../utils/utils.js');

Page({
  data: {
    currentDate: '',
    stocks: [],
    isLogin: false,
    openid: '',
    hasSelfStocks: true,
     // ✅ 新增字段：区分“无自选” vs “未登录”
     searchKeyword: '',
filteredStocks: [], // 存储筛选后的结果

  },

  async onShow() {
    this.setData({
      currentDate: util.formatDate(new Date())
    });
    await this.checkLoginStatus();

    if (this.data.isLogin) {
      await this.loadSelfStock();
      this.updateInterval = setInterval(() => {
        this.loadSelfStock();
      }, 5000);
    } else {
      this.setData({
        stocks: [],
        hasSelfStocks: false // ✅ 未登录时不显示“暂无”
      });
    }
  },

  onUnload() {
    if (this.updateInterval) {
      clearInterval(this.updateInterval);
    }
  },

  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  checkLoginStatus() {
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: 'getOpenId',
        success: async res => {
          const openid = res.result?.openid || '';
          console.log('【获取 openid】=>', openid);
  
          const db = wx.cloud.database();
  
          let isLogin = false;
          try {
            const userRes = await db.collection('user').where({ openid }).get();
            isLogin = userRes.data.length > 0 && userRes.data[0].isLogin === true;
          } catch (e) {
            console.error('检查登录状态失败:', e);
          }
  
          this.setData({
            openid,
            isLogin
          }, () => {
            console.log('【设置 isLogin】=>', isLogin);
            resolve();
          });
        },
        fail: err => {
          console.error('getOpenId 失败:', err);
          this.setData({
            openid: '',
            isLogin: false
          }, () => resolve());
        }
      });
    });
  },

  async loadSelfStock() {
    if (!this.data.isLogin) return;

    const db = wx.cloud.database();
    const res = await db.collection('selectedStock').where({ openid: this.data.openid }).get();
    const codes = (res.data[0]?.stocks || []);
    if (codes.length === 0) {
      this.setData({ stocks: [], hasSelfStocks: false }); // ✅ 登录但无自选
      return;
    }

    wx.request({
      url: `https://hq.sinajs.cn/list=${codes.join(',')}`,
      method: 'GET',
      success: (res) => {
        const data = res.data.split('\n');
        const stocks = [];
        for (let i = 0; i < data.length; i++) {
          const line = data[i].trim();
          if (line) {
            const nameMatch = line.match(/"(.+)"/);
            const name = nameMatch ? nameMatch[1].split(',')[0] : '';
            const info = line.split(',');
            if (info.length >= 34) {
              const stock = {
                code: info[0].split('=')[0].replace('var hq_str_', ''),
                name: name,
                price: parseFloat(info[3]),
                change: (((parseFloat(info[3]) - parseFloat(info[2])) / parseFloat(info[2])) * 100).toFixed(2) + '%',
                isRise: parseFloat(info[3]) >= parseFloat(info[2])
              };
              stocks.push(stock);
            }
          }
        }
        this.setData({ 
          stocks, 
          filteredStocks: stocks, // 初始显示全部
          hasSelfStocks: true 
        });
         // ✅ 有自选股
      },
      fail: (err) => {
        console.error('拉取自选股行情失败', err);
      }
    });
  },

  goToStockDetail(e) {
    const stockCode = e.currentTarget.dataset.code;
    const stockName = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: `/pages/stock/stock?name=${encodeURIComponent(stockName)}&code=${stockCode}`
    });
  },

  // ✅【新增】搜索框输入监听
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value.trim()
    });
  },

  // ✅【新增】点击“搜索”按钮触发模糊搜索
  onSearchTap() {
    const keyword = this.data.searchKeyword.trim().toLowerCase();
    const allStocks = this.data.stocks || [];

    const filtered = allStocks.filter(stock => {
      return stock.name.toLowerCase().includes(keyword) || stock.code.toLowerCase().includes(keyword);
    });

    this.setData({
      filteredStocks: filtered
    });
  }
  
});
